package cn.ylz.ylmall.account.service.impl;

import cn.ylz.ylmall.account.dao.persist.repository.IRolePermissionRepository;
import cn.ylz.ylmall.account.dao.persist.repository.IRoleRepository;
import cn.ylz.ylmall.account.dao.persist.repository.IUserRoleRepository;
import cn.ylz.ylmall.account.pojo.entity.Role;
import cn.ylz.ylmall.account.pojo.entity.RolePermission;
import cn.ylz.ylmall.account.pojo.param.RoleAddNewParams;
import cn.ylz.ylmall.account.pojo.param.RoleAddParams;
import cn.ylz.ylmall.account.pojo.param.RoleUpdateParams;
import cn.ylz.ylmall.account.pojo.vo.PageData;
import cn.ylz.ylmall.account.pojo.vo.RoleListVO;
import cn.ylz.ylmall.account.pojo.vo.RoleStandardVO;
import cn.ylz.ylmall.account.pojo.vo.UserPermissionVO;
import cn.ylz.ylmall.account.service.IRolerService;
import cn.ylz.ylmall.common.ex.ServiceException;
import cn.ylz.ylmall.common.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class RoleServiceImpl implements IRolerService {

    @Value("${ylmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IRoleRepository roleRepository;
    @Autowired
    private IRolePermissionRepository rolePermissionRepository;
    @Autowired
    private IUserRoleRepository userRoleRepository;
    @Override
    public void addnew(RoleAddNewParams roleAddNewParams) {
        int count = roleRepository.countByName(roleAddNewParams.getName());
        if (count > 0) {
            String message = "添加角色失败，角色名称已经被占用！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewParams,role);
        count = roleRepository.insert(role);
        if (count != 1) {
            String message = "添加角色失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        Long[] permissionIds = roleAddNewParams.getPermissionIds();
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Long permissionId:permissionIds){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(role.getId());
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }

        count = rolePermissionRepository.insertBatch(rolePermissionList);
        if (count < 1) {
            String message = "添加角色失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }


    }

    @Override
    public void delete(Long id) {
        RoleStandardVO queryResult = roleRepository.getStandardById(id);
        if (queryResult == null){
            String message = "删除角色失败,该角色不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        int count = roleRepository.delete(id);
        if (count != 1) {
            String message = "删除角色失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        log.debug("即将执行删除关联数据，参数：{}", id);
        count = rolePermissionRepository.deleteByRoleId(id);
        if (count < 1) {
            String message = "删除角色失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }

        log.debug("即将执行删除关联数据，参数：{}", id);
        count = userRoleRepository.deleteByRoleId(id);
        if (count < 1) {
            String message = "删除角色失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void update(Long id, RoleUpdateParams roleUpdateParams) {
        RoleStandardVO queryResult = roleRepository.getStandardById(id);
        if (queryResult == null){
            String message = "更新角色失败,该角色不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleUpdateParams,role);
        role.setId(id);
        int rows = roleRepository.update(role);
        if (rows != 1) {
            String message = "修改角色信息失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    @Override
    public RoleStandardVO getStandardById(Long id) {
        return roleRepository.getStandardById(id);
    }

    @Override
    public PageData<RoleListVO> list(Integer pageNum) {
        PageData<RoleListVO> pageData = roleRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public void add(Long roleId, RoleAddParams param) {
        Long[] permissionIds = param.getPermissionIds();
        List<RolePermission> rolePermissionList = new ArrayList<>();
        for (Long permissionId:permissionIds){
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionList.add(rolePermission);
        }
        int count = rolePermissionRepository.insertBatch(rolePermissionList);
        if (count < 1) {
            String message = "给角色新增新权限失败,请稍后再试";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public List<UserPermissionVO> PermissionsById(Long roleId) {
        return roleRepository.getPermissionByRoleId(roleId);
    }


}
